package com.oauth.google.server.youtube;

import java.util.List;

import org.springframework.beans.factory.annotation.Required;

import com.oauth.common.server.OAuthGwtController;
import com.oauth.common.server.beans.OAuthAccessToken;
import com.oauth.common.server.beans.OAuthRequestToken;
import com.oauth.common.server.util.OAuthRequestUtil;
import com.oauth.components.client.beans.OAuthUrl;
import com.oauth.google.client.beans.orkut.HttpQueryString;
import com.oauth.google.client.beans.youtube.GoogleYouTubeModel;
import com.oauth.google.client.beans.youtube.YouTubeVideo;
import com.oauth.google.client.exception.GoogleOAuthException;
import com.oauth.google.client.rpc.youtube.YouTubeRemoteService;
import com.oauth.google.server.beans.GoogleRequestToken;
import com.oauth.google.server.constants.GoogleConstants;
import com.oauth.google.server.youtube.service.YoutubeOAuthService;
import com.oauth.logging.OAuthLogger;

public class GoogleYouTubeController extends OAuthGwtController implements YouTubeRemoteService {

	private static final long serialVersionUID = -5758464341967618224L;
	private YoutubeOAuthService mYoutubeOAuthService;
	private OAuthLogger logger = OAuthLogger.getLogger(this.getClass());

	/**
	 * @param pYoutubeOAuthService
	 *            the youtubeOAuthService to set
	 */
	@Required
	public void setYoutubeOAuthService(YoutubeOAuthService pYoutubeOAuthService) {
		mYoutubeOAuthService = pYoutubeOAuthService;
	}

	@Override
	public OAuthUrl getSignInUrl() throws GoogleOAuthException {
		GoogleRequestToken requestToken;
		try {
			requestToken = mYoutubeOAuthService.getRequestToken();
		} catch (Exception e) {
			logger.error("Error in getting request token", e);
			throw new GoogleOAuthException();
		}
		OAuthRequestUtil.createTokenCookies(getHttpResponse(), requestToken,
				GoogleConstants.YOUTUBE_TOKEN_COOKIE, GoogleConstants.YOUTUBE_TOKEN_SECRETCOOKIE);
		OAuthUrl oauthUrl = new OAuthUrl();
		oauthUrl.setOAuthUrl(requestToken.getAuthorizationUrl());
		return oauthUrl;
	}

	@Override
	public GoogleYouTubeModel getYouTubeVideos(HttpQueryString pQueryString)
			throws GoogleOAuthException {
		GoogleYouTubeModel model = new GoogleYouTubeModel();
		Long memberId = OAuthRequestUtil.getMemberId(getHttpRequest());

		try {
			OAuthAccessToken accessToken = mYoutubeOAuthService.getAccessTokenFromDB(memberId);
			if (accessToken == null) {
				/* Get request token from cookie. */
				OAuthRequestToken requestToken = OAuthRequestUtil.getOAuthTokenFromCookie(
						getHttpRequest(), GoogleConstants.YOUTUBE_TOKEN_COOKIE,
						GoogleConstants.YOUTUBE_TOKEN_SECRETCOOKIE);
				if (requestToken == null) {
					model.setLoginView(true);
					return model;// Go to login page, as there is no access
					// token in
					// db and no cookie.
				} else {
					accessToken = mYoutubeOAuthService.getAccessTokenFromRequestToken(requestToken,
							pQueryString.getQueryString());

					/* Store access token for future use */
					mYoutubeOAuthService.persistAccessToken(accessToken, memberId);
					deleteGoogleCookies();
				}
			}
			// finally you got the access token which is stored in db.
			List<YouTubeVideo> videos = mYoutubeOAuthService.getYoutubeVideos(memberId);
			model.setVideos(videos);
			return model;
		} catch (Exception e) {
			deleteGoogleCookies();
			logger.error("Error in fetching youtube videos", e);
			throw new GoogleOAuthException();
		}
	}

	private void deleteGoogleCookies() {
		OAuthRequestUtil.deleteTokenCookies(getHttpResponse(),
				GoogleConstants.YOUTUBE_TOKEN_COOKIE, GoogleConstants.YOUTUBE_TOKEN_SECRETCOOKIE);
	}

}
